#region License

/*
  GShield - Game Shield
  Copyright (C) 2006-2007 WaveTech Digital Technologies, Inc.
                                http://www.wtdt.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion License

#region Includes

using System.Collections.Generic;
using System.Linq;

#endregion

namespace WaveTech.GShield.Data
{
	public static class RatingsPolicyDAO
	{
		public static RatingsPolicy GetRatingPolicyForSystem()
		{
			var policy = from p in Database.DC.RatingsPolicies
			             where p.Username == "SYSTEM"
			             select p;

			return policy.Single();
		}

		public static RatingsPolicy GetRatingPolicyForUser(string username)
		{
			var policy = from p in Database.DC.RatingsPolicies
			             where p.Username == username
			             select p;

			return policy.Single();
		}

		public static List<string> GetAllRatingPolicyUsers()
		{
			var names = from p in Database.DC.RatingsPolicies
			            select p.Username;

			return names.ToList();
		}

		public static void Delete(int policyId)
		{
			var policy = from p in Database.DC.RatingsPolicies
			             where p.Id == policyId
			             select p;

			Database.DC.RatingsPolicies.DeleteAllOnSubmit(policy);
			Database.DC.SubmitChanges();
		}

		public static void Delete(RatingsPolicy policy)
		{
			var delPolicy = from p in Database.DC.RatingsPolicies
			                where p.Id == policy.Id
			                select p;

			Database.DC.RatingsPolicies.DeleteAllOnSubmit(delPolicy);
			Database.DC.SubmitChanges();
		}

		public static void Save(RatingsPolicy policy)
		{
			Database.DC.RatingsPolicies.InsertOnSubmit(policy);
			Database.DC.SubmitChanges();
		}
	}

	#region Old RatingsPolicyDAO

	/*
  /// <summary>
  /// Ratings Policy Data Access Objects
  /// </summary>
  public class RatingsPolicyDAO
  {
    #region Save
    /// <summary>
    /// Saves or Updates a RatingsPolicy to the database
    /// </summary>
    /// <param name="ratingsPolicy">RatingsPolicy to Save or Update</param>
    /// <returns>Populated Rating Policy Object</returns>
    public RatingsPolicy Save(RatingsPolicy ratingsPolicy)
    {
      if (ratingsPolicy == null)
        throw new ArgumentException("ratingsPolicy");

      if (ratingsPolicy.Id == null)
        ratingsPolicy = Insert(ratingsPolicy);
      else
        ratingsPolicy = Update(ratingsPolicy);

      return ratingsPolicy;
    }
    #endregion Save

    #region Insert
    /// <summary>
    /// Inserts a Ratings Policy into the Database
    /// </summary>
    /// <param name="ratingsPolicy">Rating Policy to Insert</param>
    /// <returns>Populated RatingsPolicy Object</returns>
    private RatingsPolicy Insert(RatingsPolicy ratingsPolicy)
    {
      if (ratingsPolicy == null)
        throw new ArgumentException("ratingsPolicy");
      else if (ratingsPolicy.Id != null)
        throw new ArgumentException("RatingsPolicy.Id must be null to perform an insert.");

      Database db;
      DbCommand dbCommand;

      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"INSERT INTO [RatingsPolicy]
																								 ([Username]
																								 ,[AllowEC]
																								 ,[AllowE]
																								 ,[Allow10P]
																								 ,[AllowT]
																								 ,[AllowM]
																								 ,[AllowAO]
																								 ,[AllowRP]
																								 ,[AllowUnknown]
																								 ,[Hash]
																								 ,[TimeStamp])
																					 VALUES
																								 (@Username
																								 ,@AllowEC
																								 ,@AllowE
																								 ,@Allow10P
																								 ,@AllowT
																								 ,@AllowM
																								 ,@AllowAO
																								 ,@AllowRP
																								 ,@AllowUnknown
																								 ,@Hash
																								 ,@Timestamp)
																				SELECT Scope_Identity()");

      db.AddInParameter(dbCommand, "@UserName", DbType.String, ratingsPolicy.UserName);
      db.AddInParameter(dbCommand, "@AllowEC", DbType.Boolean, ratingsPolicy.AllowEC.Value);
      db.AddInParameter(dbCommand, "@AllowE", DbType.Boolean, ratingsPolicy.AllowE.Value);
      db.AddInParameter(dbCommand, "@Allow10P", DbType.Boolean, ratingsPolicy.Allow10P.Value);
      db.AddInParameter(dbCommand, "@AllowT", DbType.Boolean, ratingsPolicy.AllowT.Value);
      db.AddInParameter(dbCommand, "@AllowM", DbType.Boolean, ratingsPolicy.AllowM.Value);
      db.AddInParameter(dbCommand, "@AllowAO", DbType.Boolean, ratingsPolicy.AllowAO.Value);
      db.AddInParameter(dbCommand, "@AllowRP", DbType.Boolean, ratingsPolicy.AllowRP.Value);
      db.AddInParameter(dbCommand, "@AllowUnknown", DbType.Boolean, ratingsPolicy.AllowUnknown.Value);
      db.AddInParameter(dbCommand, "@Timestamp", DbType.DateTime, DateTime.Now);
      db.AddInParameter(dbCommand, "@Hash", DbType.String, ratingsPolicy.ComputeHash());

      ratingsPolicy.Id = int.Parse(db.ExecuteScalar(dbCommand).ToString());

      return ratingsPolicy;
    }
    #endregion Insert

    #region Update
    /// <summary>
    /// Updates a RatingsPolicy object in the database
    /// </summary>
    /// <param name="ratingsPolicy">RatingsPolicy to Update</param>
    /// <returns>Copy of the presisted RatingsPolicy object</returns>
    private RatingsPolicy Update(RatingsPolicy ratingsPolicy)
    {
      if (ratingsPolicy == null)
        throw new ArgumentException("ratingsPolicy");
      else if (ratingsPolicy.Id == null)
        throw new ArgumentException("RatingsPolicy.Id must be not null to perform an update.");

      Database db;
      DbCommand dbCommand;

      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"UPDATE [RatingsPolicy]
																						SET [Username] = @Username
																								,[AllowEC] = @AllowEC
																								,[AllowE] = @AllowE
																								,[Allow10P] = @Allow10P
																								,[AllowT] = @AllowT
																								,[AllowM] = @AllowM
																								,[AllowAO] = @AllowAO
																								,[AllowRP] = @AllowRP
																								,[AllowUnknown] = @AllowUnknown
																								,[Timestamp] = @Timestamp
																								,[Hash] = @Hash
																						WHERE (Id = @Id)");

      db.AddInParameter(dbCommand, "@UserName", DbType.String, ratingsPolicy.UserName);
      db.AddInParameter(dbCommand, "@AllowEC", DbType.Boolean, ratingsPolicy.AllowEC.Value);
      db.AddInParameter(dbCommand, "@AllowE", DbType.Boolean, ratingsPolicy.AllowE.Value);
      db.AddInParameter(dbCommand, "@Allow10P", DbType.Boolean, ratingsPolicy.Allow10P.Value);
      db.AddInParameter(dbCommand, "@AllowT", DbType.Boolean, ratingsPolicy.AllowT.Value);
      db.AddInParameter(dbCommand, "@AllowM", DbType.Boolean, ratingsPolicy.AllowM.Value);
      db.AddInParameter(dbCommand, "@AllowAO", DbType.Boolean, ratingsPolicy.AllowAO.Value);
      db.AddInParameter(dbCommand, "@AllowRP", DbType.Boolean, ratingsPolicy.AllowRP.Value);
      db.AddInParameter(dbCommand, "@AllowUnknown", DbType.Boolean, ratingsPolicy.AllowUnknown.Value);
      db.AddInParameter(dbCommand, "@Timestamp", DbType.DateTime, DateTime.Now);
      db.AddInParameter(dbCommand, "@Hash", DbType.String, ratingsPolicy.ComputeHash());
      db.AddInParameter(dbCommand, "@Id", DbType.Int32, ratingsPolicy.Id.Value);

      db.ExecuteNonQuery(dbCommand);

      return ratingsPolicy;
    }
    #endregion Update

    #region Does Rating Policy Exist
    /// <summary>
    /// Checks the database to see if a RatingsPolicy exists for a specific user
    /// </summary>
    /// <param name="username">UserName to check</param>
    /// <returns>True if a RatingsPolicy exists, otherwise false</returns>
    public bool DoesRatingPolicyExist(string username)
    {
      if (username == null || username.Length <= 0)
        throw new ArgumentException("username");

      Database db;
      DbCommand dbCommand;

      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"SELECT Id, Username, AllowEC, AllowE, Allow10P, AllowT, 
																							AllowM, AllowAO, AllowRP, AllowUnknown, [Timestamp]
																					FROM RatingsPolicy
																					WHERE (Username = @Username)");

      db.AddInParameter(dbCommand, "@UserName", DbType.String, username);

      object o = db.ExecuteScalar(dbCommand);

      if (o == null)
        return false;
      else
        return true;
    }
    #endregion Does Rating Policy Exist

    #region Delete
    /// <summary>
    /// Deletes the specified RatingsPolicy from the database
    /// </summary>
    /// <param name="ratingsPolicy">RatingsPolicy object to delete</param>
    public void Delete(RatingsPolicy ratingsPolicy)
    {
      if (ratingsPolicy == null || !ratingsPolicy.Id.HasValue)
        throw new ArgumentNullException("ratingsPolicy");
      else if (ratingsPolicy.Id.HasValue == false)
        throw new ArgumentException("RatingsPolicy.Id must have a value to perform a delete.");

      Database db;
      DbCommand dbCommand;

      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"DELETE
																						FROM RatingsPolicy
																						WHERE ([Id] = @Id)");

      db.AddInParameter(dbCommand, "@Id", DbType.Int32, ratingsPolicy.Id.Value);

      db.ExecuteNonQuery(dbCommand);
    }
    #endregion Delete

    #region Get Rating Policy
    /// <summary>
    /// Gets the RatingPolicy for the supplied user
    /// </summary>
    /// <param name="userName">UserName to get the policy for</param>
    /// <returns>Populated RatingsPolicy object for the user</returns>
    public RatingsPolicy GetRatingPolicy(string userName)
    {
      if (userName == null || userName.Length <= 0)
        throw new ArgumentException("userName");

      Database db = DatabaseFactory.CreateDatabase();
			DbCommand dbCommand = db.GetSqlStringCommand(@"SELECT Id, Username, AllowEC, AllowE, Allow10P, AllowT, 
																							AllowM, AllowAO, AllowRP, AllowUnknown, [Timestamp]
																					FROM RatingsPolicy
																					WHERE (Username = @Username)");

      db.AddInParameter(dbCommand, "@UserName", DbType.String, userName);

      return FillRatingsPolicyObject(db.ExecuteReader(dbCommand));
    }
    #endregion Get Rating Policy

    #region Get Rating Policy For System
    /// <summary>
    /// Gets the Systems RatingPolicy
    /// </summary>
    /// <returns>Populated Systems RatingPolicy object</returns>
    public RatingsPolicy GetRatingPolicyForSystem()
    {
			return GetRatingPolicy("SYSTEM");
    }
    #endregion Get Rating Policy For System

    #region Get Rating Policy Users
    /// <summary>
    /// Returns a list of all users who have a RatingPolicy
    /// </summary>
    /// <returns>String array of users with a RatingsPolicy</returns>
    public string[] GetRatingsPolicyUsers()
    {
      Database db;
      DbCommand dbCommand;
      ArrayList lst;

      db = DatabaseFactory.CreateDatabase();
			dbCommand = db.GetSqlStringCommand(@"SELECT [Username]
																						FROM RatingsPolicy");

      lst = new ArrayList();
      IDataReader r = db.ExecuteReader(dbCommand);

      while (r.Read())
      {
        lst.Add(r[0].ToString());
      }

			return (string[])lst.ToArray(typeof(string));
    }
    #endregion Get Rating Policy Users

    #region Fill Rating Policy Object
    /// <summary>
    /// Populates a RatingPolicy object from a DataReader
    /// </summary>
    /// <param name="reader">DataReader to use to populate</param>
    /// <returns>Populated RatingsPolicy object</returns>
    private RatingsPolicy FillRatingsPolicyObject(IDataReader reader)
    {
      if (reader == null)
        throw new ArgumentNullException("reader");

      RatingsPolicy policy = null;

      if (reader.Read())
      {
        policy = new RatingsPolicy();

        if (!reader.IsDBNull(reader.GetOrdinal("Id")))
          policy.Id = reader.GetInt32(reader.GetOrdinal("Id"));

        if (!reader.IsDBNull(reader.GetOrdinal("UserName")))
          policy.UserName = reader.GetString(reader.GetOrdinal("UserName"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowEC")))
          policy.AllowEC = reader.GetBoolean(reader.GetOrdinal("AllowEC"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowE")))
          policy.AllowE = reader.GetBoolean(reader.GetOrdinal("AllowE"));

        if (!reader.IsDBNull(reader.GetOrdinal("Allow10P")))
          policy.Allow10P = reader.GetBoolean(reader.GetOrdinal("Allow10P"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowT")))
          policy.AllowT = reader.GetBoolean(reader.GetOrdinal("AllowT"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowM")))
          policy.AllowM = reader.GetBoolean(reader.GetOrdinal("AllowM"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowAO")))
          policy.AllowAO = reader.GetBoolean(reader.GetOrdinal("AllowAO"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowRP")))
          policy.AllowRP = reader.GetBoolean(reader.GetOrdinal("AllowRP"));

        if (!reader.IsDBNull(reader.GetOrdinal("AllowUnknown")))
          policy.AllowUnknown = reader.GetBoolean(reader.GetOrdinal("AllowUnknown"));

        if (!reader.IsDBNull(reader.GetOrdinal("Timestamp")))
          policy.Timestamp = reader.GetDateTime(reader.GetOrdinal("Timestamp"));
      }

      return policy;
    }
    #endregion Fill Rating Policy Object
  }
    */

	#endregion Old RatingsPolicyDAO
}